package com.hyh.eblog.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyh.eblog.common.lang.Result;
import com.hyh.eblog.entity.Post;
import com.hyh.eblog.entity.UserCollection;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Summerday
 * @since 2020-10-19
 */
@Controller
public class UserCollectionController extends BaseController {
    /**
     * 判断用户是否收藏了文章
     *
     * @param pid
     * @return
     */
    @ResponseBody
    @PostMapping("/collection/find")
    public Result find(Long pid) {
        int count = userCollectionService.count(new QueryWrapper<UserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid));
        boolean isCollect = count > 0;
        return Result.success(MapUtil.of("collection", isCollect));
    }

    @ResponseBody
    @PostMapping("/collection/add")
    public Result add(Long pid) {
        Post post = postService.getById(pid);
        Assert.isTrue(post != null, "该帖子已经被删除");
        int count = userCollectionService.count(new QueryWrapper<UserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid));
        if (count > 0) return Result.fail("已经收藏该文章");
        UserCollection uc = new UserCollection();
        uc.setUserId(getProfileId());
        uc.setPostId(pid);
        uc.setPostUserId(post.getUserId());
        userCollectionService.save(uc);
        return Result.success();
    }

    @ResponseBody
    @PostMapping("/collection/remove")
    public Result remove(Long pid) {
        Post post = postService.getById(pid);
        Assert.isTrue(post != null, "该帖子已经被删除");
        userCollectionService.remove(new QueryWrapper<UserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid));
        return Result.success();
    }
}
